#include "studentManager.h"
#include <string>
#include <iostream>
#include <algorithm> // 包含 std::sort 函数

#include "primarystudent.h"
#include "middlestudent.h"
#include "collegestudent.h"

using namespace std;

StudentManager::~StudentManager()
{
    for (Student* student : students) {
        if(student != nullptr)
            delete student;
    }
}

void StudentManager::addStudent() {
    cout << "\n=== 添加学生信息 ===" << endl;
    cout << "1. 添加小学生" << endl;
    cout << "2. 添加中学生" << endl;
    cout << "3. 添加大学生" << endl;
    cout << "请选择: ";

    int choice;
    cin >> choice;
    cin.ignore();

    Student* newStudent = nullptr;
    switch (choice) {
    case 1:
        newStudent = new PrimaryStudent();
        break;
    case 2:
        newStudent = new MiddleStudent();
        break;
    case 3:
        newStudent = new CollegeStudent();
        break;
    default:
        cout << "无效的选择！" << endl;
        return;
    }

    newStudent->input();

     //检查学号是否重复
    if (isStudentIdExists(newStudent->getStudentId())) {
        cout << "错误：该学号已存在！" << endl;
        delete newStudent;
        return;
    }

    students.push_back(newStudent);
    cout << "添加成功！" << endl;
    std::cout << "添加成功" << endl;
}

void StudentManager::queryStudent() {
    if (students.empty()) {
        cout << "系统中没有学生记录！" << endl;
        return;
    }

    cout << "\n=== 查询学生信息 ===" << endl;
    cout << "1. 按学号查询" << endl;
    cout << "2. 按姓名查询" << endl;
    cout << "请选择查询方式: ";

    int choice;
    cin >> choice;
    cin.ignore();

    string searchTerm;
    bool found = false;

    switch (choice) {
    case 1:
        cout << "请输入学号: ";
        getline(cin, searchTerm);
        for (Student* student : students) {
            if (student->getStudentId() == searchTerm) {
                student->display();
                found = true;
                break;
            }
        }
        break;
    case 2:
        cout << "请输入姓名: ";
        getline(cin, searchTerm);
        for (const auto& student : students) {
            if (student->getName() == searchTerm) {
                student->display();
                found = true;
            }
        }
        break;
    default:
        cout << "无效的选择！" << endl;
        return;
    }

    if (!found) {
        cout << "未找到匹配的学生记录！" << endl;

    }
}

void StudentManager::displayAll() const {
    if (students.empty()) {
        cout << "系统中没有学生记录！" << endl;
        return;
    }

    cout << "\n=== 所有学生信息 ===" << endl;
    for (const auto& student : students) {
        student->display();
        cout << "------------------------" << endl;
    }
}

void StudentManager::editStudent()
{
    if (students.empty()) {
        cout << "系统中没有学生记录！" << endl;
        return;
    }

    cout << "\n=== 编辑学生信息 ===" << endl;
    cout << "1. 按学号查询并编辑" << endl;
    cout << "2. 按姓名查询并编辑" << endl;
    cout << "请选择查询方式: ";

    int choice;
    cin >> choice;
    cin.ignore();

    string searchTerm;
    bool found = false;
    Student* studentToEdit = nullptr;

    switch (choice) {
    case 1: // 按学号查询
        cout << "请输入学号: ";
        getline(cin, searchTerm);
        studentToEdit = findStudentById(searchTerm);
        if (studentToEdit) {
            found = true;
        }
        break;

    case 2: // 按姓名查询
        cout << "请输入姓名: ";
        getline(cin, searchTerm);
        for (Student* student : students) {
            if (student->getName() == searchTerm) {
                studentToEdit = student;
                found = true;
                break;
            }
        }
        break;

    default:
        cout << "无效的选择！" << endl;
        return;
    }

    if (!found) {
        cout << "未找到匹配的学生记录！" << endl;
        return;
    }

    // 显示当前学生信息
    cout << "\n当前学生信息：" << endl;
    studentToEdit->display();

    // 编辑菜单
    cout << "\n=== 编辑选项 ===" << endl;
    cout << "1. 修改学号" << endl;
    cout << "2. 修改姓名" << endl;
    cout << "3. 修改性别" << endl;
    cout << "4. 修改年龄" << endl;
    cout << "5. 修改班级" << endl;
    cout << "6. 修改成绩" << endl;
    cout << "0. 返回主菜单" << endl;
    cout << "请选择要编辑的字段: ";

    int editChoice;
    cin >> editChoice;
    cin.ignore();

    switch (editChoice) {
    case 1: { // 修改学号
        string newStudentId;
        cout << "请输入新学号: ";
        getline(cin, newStudentId);

        // 检查新学号是否已存在
        if (isStudentIdExists(newStudentId)) {
            cout << "错误：该学号已存在！" << endl;
            return;
        }

        studentToEdit->studentId = newStudentId;
        cout << "学号修改成功！" << endl;
        break;
    }

    case 2: { // 修改姓名
        string newName;
        cout << "请输入新姓名: ";
        getline(cin, newName);
        studentToEdit->name = newName;
        cout << "姓名修改成功！" << endl;
        break;
    }

    case 3: { // 修改性别
        char newGender;
        cout << "请输入新性别(M/F): ";
        cin >> newGender;
        cin.ignore();
        studentToEdit->gender = newGender;
        cout << "性别修改成功！" << endl;
        break;
    }

    case 4: { // 修改年龄
        int newAge;
        cout << "请输入新年龄: ";
        cin >> newAge;
        cin.ignore();
        studentToEdit->age = newAge;
        cout << "年龄修改成功！" << endl;
        break;
    }

    case 5: { // 修改班级
        string newClassName;
        cout << "请输入新班级: ";
        getline(cin, newClassName);
        studentToEdit->className = newClassName;
        cout << "班级修改成功！" << endl;
        break;
    }

    case 6: { // 修改成绩
        if (PrimaryStudent* primaryStudent = dynamic_cast<PrimaryStudent*>(studentToEdit)) {
            cout << "请输入新英语成绩: ";
            cin >> primaryStudent->english;
            cout << "请输入新数学成绩: ";
            cin >> primaryStudent->math;
            cout << "请输入新语文成绩: ";
            cin >> primaryStudent->chinese;
            cin.ignore();
            cout << "成绩修改成功！" << endl;
        }
        else if (MiddleStudent* middleStudent = dynamic_cast<MiddleStudent*>(studentToEdit)) {
            cout << "请输入新英语成绩: ";
            cin >> middleStudent->english;
            cout << "请输入新数学成绩: ";
            cin >> middleStudent->math;
            cout << "请输入新语文成绩: ";
            cin >> middleStudent->chinese;
            cout << "请输入新地理成绩: ";
            cin >> middleStudent->geography;
            cout << "请输入新历史成绩: ";
            cin >> middleStudent->history;
            cin.ignore();
            cout << "成绩修改成功！" << endl;
        }
        else if (CollegeStudent* collegeStudent = dynamic_cast<CollegeStudent*>(studentToEdit)) {
            cout << "请输入新英语成绩: ";
            cin >> collegeStudent->english;
            cout << "请输入新程序设计成绩: ";
            cin >> collegeStudent->programming;
            cout << "请输入新高等数学成绩: ";
            cin >> collegeStudent->advancedMath;
            cin.ignore();
            cout << "成绩修改成功！" << endl;
        }
        else {
            cout << "错误：未知的学生类型！" << endl;
        }
        break;
    }

    case 0: // 返回主菜单
        cout << "取消编辑，返回主菜单。" << endl;
        break;

    default:
        cout << "无效的选择！" << endl;
        break;
    }

    // 显示修改后的学生信息
    cout << "\n修改后的学生信息：" << endl;
    studentToEdit->display();
}

void StudentManager::deleteStudent() {
    if (students.empty()) {
        cout << "系统中没有学生记录，无法删除！" << endl;
        return;
    }

    cout << "\n=== 删除学生信息 ===" << endl;
    cout << "1. 按学号删除" << endl;
    cout << "2. 按姓名删除" << endl;
    cout << "请选择删除方式: ";

    int choice;
    cin >> choice;
    cin.ignore();

    string searchTerm;
    bool found = false;

    switch (choice) {
    case 1: { // 按学号删除
        cout << "请输入要删除的学生学号: ";
        getline(cin, searchTerm);

        auto it = students.begin();
        while (it != students.end()) {
            if ((*it)->getStudentId() == searchTerm) {
                delete* it; // 释放内存
                it = students.erase(it); // 从容器中移除
                found = true;
                cout << "学号为 " << searchTerm << " 的学生已删除！" << endl;
                break;
            }
            else {
                ++it;
            }
        }
        break;
    }

    case 2: { // 按姓名删除
        cout << "请输入要删除的学生姓名: ";
        getline(cin, searchTerm);

        auto it = students.begin();
        while (it != students.end()) {
            if ((*it)->getName() == searchTerm) {
                delete* it; // 释放内存
                it = students.erase(it); // 从容器中移除
                found = true;
                cout << "姓名为 " << searchTerm << " 的学生已删除！" << endl;
                break;
            }
            else {
                ++it;
            }
        }
        break;
    }

    default:
        cout << "无效的选择！" << endl;
        return;
    }

    if (!found) {
        cout << "未找到匹配的学生记录！" << endl;
    }
}

void StudentManager::statistics() const
{
    if (students.empty()) {
        cout << "系统中没有学生记录！" << endl;
        return;
    }

    cout << "\n=== 统计功能 ===" << endl;
    cout << "1. 统计学生人数" << endl;
    cout << "2. 统计总分" << endl;
    cout << "3. 统计单科平均分" << endl;
    cout << "请选择统计方式: ";

    int choice;
    cin >> choice;
    cin.ignore();

    switch (choice) {
    case 1: { // 统计学生人数
        cout << "学生总人数: " << students.size() << endl;
        break;
    }

    case 2: { // 统计总分
        double totalScore = 0;
        for (const auto& student : students) {
            totalScore += student->calculateTotalScore();
        }
        cout << "所有学生的总分: " << totalScore << endl;
        break;
    }

    case 3: { // 统计单科平均分
        double englishSum = 0, mathSum = 0, chineseSum = 0;
        auto count = students.size();

        for (const auto& student : students) {
            if (PrimaryStudent* primaryStudent = dynamic_cast<PrimaryStudent*>(student)) {
                englishSum += primaryStudent->english;
                mathSum += primaryStudent->math;
                chineseSum += primaryStudent->chinese;
            }
        }

        cout << "英语平均分: " << englishSum / count << endl;
        cout << "数学平均分: " << mathSum / count << endl;
        cout << "语文平均分: " << chineseSum / count << endl;
        break;
    }

    default:
        cout << "无效的选择！" << endl;
        break;
    }
}

void StudentManager::saveToFile()
{
    if (students.empty()) {
        cout << "系统中没有学生记录，无需保存！" << endl;
        return;
    }

    ofstream outFile("students.dat", ios::out | ios::binary);
    if (!outFile) {
        cout << "文件打开失败，无法保存数据！" << endl;
        return;
    }

    // 写入学生数量
    size_t studentCount = students.size();
    outFile.write(reinterpret_cast<const char*>(&studentCount), sizeof(studentCount));

    // 写入每个学生的数据
    for (const auto& student : students) {
        student->save(outFile);
    }

    outFile.close();
    cout << "学生数据已保存到文件！" << endl;
}

void StudentManager::loadFromFile()
{
    ifstream inFile("students.dat", ios::in | ios::binary);
    if (!inFile) {
        cout << "文件打开失败，无法加载数据！" << endl;
        return;
    }

    // 清空当前学生记录
    for (auto& student : students) {
        delete student;
    }
    students.clear();

    // 读取学生数量
    size_t studentCount;
    inFile.read(reinterpret_cast<char*>(&studentCount), sizeof(studentCount));

    // 读取每个学生的数据
    for (size_t i = 0; i < studentCount; ++i) {
        string type;
        getline(inFile, type, '\0'); // 读取学生类型

        Student* student = nullptr;
        if (type == "PrimaryStudent") {
            student = new PrimaryStudent();
        }
        else if (type == "MiddleStudent") {
            student = new MiddleStudent();
        }
        else if (type == "CollegeStudent") {
            student = new CollegeStudent();
        }

        if (student) {
            student->load(inFile);
            students.push_back(student);
        }
    }

    inFile.close();
    cout << "学生数据已从文件加载！" << endl;
}

void StudentManager::sortStudents()
{
    if (students.empty()) {
        cout << "系统中没有学生记录！" << endl;
        return;
    }

    // 显示排序选项菜单
    cout << "\n=== 成绩排序 ===" << endl;
    cout << "1. 按英语成绩排序" << endl;
    cout << "2. 按数学成绩排序" << endl;
    cout << "3. 按语文成绩排序" << endl;
    cout << "4. 按总分排序" << endl;
    cout << "请选择排序方式: ";

    int choice;
    cin >> choice;
    cin.ignore();

    // 根据用户选择进行排序
    switch (choice) {
    case 1: // 按英语成绩排序
        std::sort(students.begin(), students.end(), [](Student* a, Student* b) {
            return dynamic_cast<PrimaryStudent*>(a)->english > dynamic_cast<PrimaryStudent*>(b)->english;
            });
        cout << "已按英语成绩排序！" << endl;
        break;

    case 2: // 按数学成绩排序
        std::sort(students.begin(), students.end(), [](Student* a, Student* b) {
            return dynamic_cast<PrimaryStudent*>(a)->math > dynamic_cast<PrimaryStudent*>(b)->math;
            });
        cout << "已按数学成绩排序！" << endl;
        break;

    case 3: // 按语文成绩排序
        std::sort(students.begin(), students.end(), [](Student* a, Student* b) {
            return dynamic_cast<PrimaryStudent*>(a)->chinese > dynamic_cast<PrimaryStudent*>(b)->chinese;
            });
        cout << "已按语文成绩排序！" << endl;
        break;

    case 4: // 按总分排序
        std::sort(students.begin(), students.end(), [](Student* a, Student* b) {
            return a->calculateTotalScore() > b->calculateTotalScore();
            });
        cout << "已按总分排序！" << endl;
        break;

    default:
        cout << "无效的选择！" << endl;
        return;
    }

    // 显示排序后的学生信息
    displayAll();
}

bool StudentManager::isStudentIdExists(const string& id) const
{
    return findStudentById(id) != nullptr;
}

Student* StudentManager::findStudentById(const string& id) const
{
    for (const auto& stu : students)
    {
        if (stu->getStudentId() == id)
        {
            return stu;
        }
    }
    return nullptr;
}
